package com.quan.mall.commons.mq.listener;

import com.quan.commons.core.utils.DateUtils;
import com.quan.mall.service.OmsOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class OrderConsumer {
	
	@Autowired
	private OmsOrderService omsOrderService;

	/**
	 * 监听死信队列,定时关单
	 */
	@RabbitListener(queues = { "ORDER-CLOSE-QUEUE" })
	public void closeOrder(String orderSn, Channel channel, Message message) {
		try {
			log.debug("==>监听死信队列，定时关单，订单号=[{}]，时间=[{}]", orderSn, DateUtils.getDateTime());

			// 关单
			if (omsOrderService.closeOrderMQ(Long.parseLong(orderSn))) {
				// 如果关单成功，发送消息给库存系统，释放库存，上面关闭订单是已完成，不用再操作
			}
			// 如果关单失败，说明订单可能已被关闭，或用户已付款，直接确认消息
			// 手动ACK
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		} catch (IOException e) {
			try {
				// 消费失败后重新入队
				channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
			} catch (IOException e1) {
				log.error("释放库存失败,orderId=[{}]", orderSn);
			}
		}
	}
}
